package com.atguigu.edu.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.edu.realtime.app.func.DorisSinkFunction;
import com.atguigu.edu.realtime.beans.TrafficKeyWordViewBean;
import com.atguigu.edu.realtime.beans.TrafficSessionPageViewBean;
import com.atguigu.edu.realtime.utils.DateFormatUtil;
import com.atguigu.edu.realtime.utils.KeywordUtil;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.util.List;

public class DwsTrafficSourceKeywordPageViewWindow {
    public static void main(String[] args) {
        //基本环境准备
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(5);
        //检查点配置
        /*env.enableCheckpointing(5000l);
        env.getCheckpointConfig().setCheckpointTimeout(60000l);
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000l);
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(10)));
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/edu/ck");
        System.setProperty("HADOOP_USER_NAME","atguigu");*/
        //读取kafka的dwd_traffic_page_log主题
        DataStreamSource<String> jsonStrDs = env.fromSource(MyKafkaUtil.getKafkaSource("dwd_traffic_page_log", "dws_traffic_Keyword_group"),
                WatermarkStrategy.noWatermarks(), "kafkassorce");

        //转换数据类型
        SingleOutputStreamOperator<JSONObject> jsonObj = jsonStrDs.map(JSON::parseObject);
        //jsonObj.print(">>>>");
        //过滤数据
        SingleOutputStreamOperator<JSONObject> filterDs = jsonObj.filter(
                new FilterFunction<JSONObject>() {
                    @Override
                    public boolean filter(JSONObject jsonObj) throws Exception {
                        JSONObject page = jsonObj.getJSONObject("page");
                        String item = page.getString("item");
                        String itemType = page.getString("item_type");
                        //System.out.println(item +"::"+ lastPageId + "::" +itemType);
                        return StringUtils.isNotEmpty(item) &&  "keyword".equals(itemType);
                    }
                }
        );
        //filterDs.print();
        //封装bean
        SingleOutputStreamOperator<TrafficKeyWordViewBean> beanDs = filterDs.process(
                new ProcessFunction<JSONObject, TrafficKeyWordViewBean>() {
                    @Override
                    public void processElement(JSONObject jsonObj, ProcessFunction<JSONObject, TrafficKeyWordViewBean>.Context ctx, Collector<TrafficKeyWordViewBean> out) throws Exception {
                        JSONObject page = jsonObj.getJSONObject("page");
                        Long ts = jsonObj.getLong("ts");
                        String item = page.getString("item");
                        List<String> analyze = KeywordUtil.analyze(item);
                        for (String word : analyze) {
                            out.collect(new TrafficKeyWordViewBean(
                                    "",
                                    "",
                                    "",
                                    word,
                                    1l,
                                    ts

                            ));
                        }
                    }
                }
        );
        //beanDs.print();
        //设定水位线
        SingleOutputStreamOperator<TrafficKeyWordViewBean> watermarksDs = beanDs.assignTimestampsAndWatermarks(
                WatermarkStrategy.<TrafficKeyWordViewBean>forMonotonousTimestamps()
                        .withTimestampAssigner(
                                new SerializableTimestampAssigner<TrafficKeyWordViewBean>() {
                                    @Override
                                    public long extractTimestamp(TrafficKeyWordViewBean element, long recordTimestamp) {
                                        return element.getTs();
                                    }
                                }
                        )
        );
        //分组开窗聚合
        SingleOutputStreamOperator<TrafficKeyWordViewBean> reduceDs = watermarksDs.keyBy(
                new KeySelector<TrafficKeyWordViewBean, String>() {
                    @Override
                    public String getKey(TrafficKeyWordViewBean value) throws Exception {
                        return value.getKeyWord();
                    }
                }
        ).window(
                TumblingEventTimeWindows.of(Time.seconds(10))
        ).reduce(
                new ReduceFunction<TrafficKeyWordViewBean>() {
                    @Override
                    public TrafficKeyWordViewBean reduce(TrafficKeyWordViewBean value1, TrafficKeyWordViewBean value2) throws Exception {
                        value1.setWordSum(value1.getWordSum() + value2.getWordSum());
                        return value1;
                    }
                },
                new ProcessWindowFunction<TrafficKeyWordViewBean, TrafficKeyWordViewBean, String, TimeWindow>() {
                    @Override
                    public void process(String s, ProcessWindowFunction<TrafficKeyWordViewBean, TrafficKeyWordViewBean, String, TimeWindow>.Context context, Iterable<TrafficKeyWordViewBean> elements, Collector<TrafficKeyWordViewBean> out) throws Exception {
                        String stt = DateFormatUtil.toYmdHms(context.window().getStart());
                        String edt = DateFormatUtil.toYmdHms(context.window().getEnd());
                        String date = DateFormatUtil.toDate(context.window().getStart());

                        TrafficKeyWordViewBean viewBean = elements.iterator().next();
                        viewBean.setStt(stt);
                        viewBean.setEdt(edt);
                        viewBean.setCurDate(date);

                        out.collect(viewBean);

                    }
                }
        );
        reduceDs.print(">>>>");
        //写入到doris
        reduceDs.addSink(new DorisSinkFunction<TrafficKeyWordViewBean>("dws_traffic_keyword_view_window"));

        try {
            env.execute();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
